package com.atguigu.config;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.entity.Admin;
import com.atguigu.service.AdminService;
import com.atguigu.service.PermissionService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Component
public class MyUserDetailService implements UserDetailsService {
    @Reference
    private AdminService adminService;
    @Reference
    private PermissionService permissionService;
//   登录时，SpringSecurity会自动调用该方法，并将用户名传入到该方法中
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//      根据用户名查询Admin对象的方法
        Admin admin=adminService.getAdminByUsername(username);
        if (admin==null){
            throw new UsernameNotFoundException("用户不存在");
        }
//        获取当前用户权限码的方法
        List<String> permissionCodes=permissionService.getPermissionCodesByAdminId(admin.getId());
//        创建一个用于授权的集合
        List<GrantedAuthority> grantedAuthorities=new ArrayList<>();
        for (String permissionCode : permissionCodes) {
            if(!StringUtils.isEmpty(permissionCode)) {
                SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(permissionCode);
                grantedAuthorities.add(simpleGrantedAuthority);
            }
        }
//        给用户授权
//        return new User(username,admin.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList(""));
        return new User(username,admin.getPassword(), grantedAuthorities);
    }
}
